import hxjson2.JSON;

class Main {
	public static function main()
	{
		//example_wrapper(encode_example, "encoding");
		//example_wrapper(decode_example_1, "decoding");
		//example_wrapper(decode_example_2, "decoding");
		example_wrapper(decode_example_3, "decoding");
	}


	public static function encode_example()
	{
		var tuple : Dynamic = {x:0,y:1,z:2};
		trace("encoded: " + JSON.encode(tuple));
		tuple = JSON.decode(JSON.encode(tuple));
		trace(Std.is(tuple.x, Int));
		trace(Std.is(tuple.y, Int));
		trace(Std.is(tuple.z, Int));
	}

	public static function decode_example_1()
	{
		
		var str = '{ "x":1, "y":2, "z":3 }';
		trace(Std.is(str, String));
		trace(str);
		var tuple : Dynamic  = JSON.decode(str);
		trace(Std.is(tuple.x, Int));
		trace(Std.is(tuple.y, Int));
		trace(Std.is(tuple.z, Int));

		// TODO - use 'massload' to download remote stuff
	}

	public static function decode_example_2()
	{
		var str = '{ "x--":1, "-_y":2, "z-":3 }';
		trace(Std.is(str, String));
		trace(str);
		var tuple : Dynamic  = JSON.decode(str);
		var fields : Array<String> = Reflect.fields(tuple);
		for (f in fields)
		{
			if(Std.is(Reflect.field(tuple,f), Int))
			{
				var i : Int = Reflect.field(tuple,f);
				trace(f + " : " +  i);
			}
		}
	}

	public static function decode_example_3()
	{
		// ternary tree
		var str = '
			{
				"--x__" : {
					"--a" : {
						"__p" : 31
						, "q" : 32
						, "--r" : 33
					}
					, "b--" : 12
					, "--c--" : 13
				}
				, "-_y_-" : 2
				, "__z--" : {
					"a--" : [31,32,33,34,35]
					, "--b" : 32
					, "-c__"  : [55, 56, 57, 58, 59, 60]
				}
			}	
		';
		var obj = JSON.decode(str);
		preorder_traversal(obj, 0);
	}

	public static function preorder_traversal(obj:Dynamic, depth : Int)
	{
		var fields : Array<String> = Reflect.fields(obj);
		for (f in fields)
		{
			trace(f);
			var value : Dynamic = Reflect.field(obj,f);
			if (Std.is(value, Int))
			{
				trace ("depth " + depth + ", value is an Integer: " + value);
			} else if (Std.is(value, Array))
			{
				var j : Int = 0;
				var value_ : Array<Dynamic> = cast(value, Array<Dynamic>);
				for (i in value_)
				{
					j += i;
				}
				trace ("depth " + depth + ", value is an Array of Integers. The sum is: " + j);
			}else if (Std.is(value,Dynamic))
			{
				trace ("depth " + depth + ", value is another object: go into recursion");
				preorder_traversal(value, depth + 1);
			}else
			{
				trace("depth " + depth + ",Something went horribly wrong");
				return;
			}
		}
	}

	public static function example_wrapper(func : Void -> Void, str:String)
	{
		trace("Start json " + str + " example");
		func();
		trace("End json " + str + " example");
	}
}
